/**
 * Created by 60132 on 2018/9/6.
 */
/**
 * 初始化事故实例详情对话框
 */
var AccidentInfoDlg = {
    accidentInfoData: {}
    ,lineId:null
    , accidentTypeTreeInstance: null
    , accidentId: null
    , lineTreeInstance: null
    , stationTreeInstance: null
    , emergencyTreeInstatce: null
    , counterplanId:null
    ,uploadInstance:null
    ,itemTemplate: $("#itemTemplate").html()
    , count: $("#itemSize").val()
    ,processJson:null //历史事故实例处置流程jso数据
    ,disposalJson:null  //新增历史案例处置操作
    ,alarmprocessJson:null //处置流程编辑后保存的处置流程操作
    ,currentIndex:$("#currentIndex").val()
    ,accidentInfo: $("#accident_info").val()
    ,dispositionStep:[]//处置阶段操作流程id
    , validateFields:{
        name: {
            validators: {
                notEmpty: {
                    message: '名称不能为空'
                }
            }
        }
        ,accidentTypeName:{
            validators: {
                notEmpty: {
                    message: '事故类型不能为空'
                }
            }
        }
    }
};
/**
 * item获取新的ID
 * @returns {string}
 */
AccidentInfoDlg.newId = function () {
    if(this.count == undefined){
        this.count = 0;
    }
    this.count = this.count + 1;
    return "dictItem" + this.count;
};
/**
 * 清除数据
 */
AccidentInfoDlg.clearData = function () {
    this.accidentInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
AccidentInfoDlg.set = function (key, val) {
    this.accidentInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
AccidentInfoDlg.get = function (key) {
    return $("#" + key).val();
};

/**
 * 关闭此对话框
 */
AccidentInfoDlg.close = function () {
    parent.layer.close(window.parent.Accident.layerIndex);
};

/**
 * 添加条目
 */
AccidentInfoDlg.addItem = function () {
    $("#itemsArea").append(this.itemTemplate);
    $("#dictItem").attr("id", this.newId());
};

/**
 * 删除item
 */
AccidentInfoDlg.deleteItem = function (event) {
    var obj = Feng.eventParseObject(event);
    obj.parent().parent().remove();
};
/**
 * 收集数据
 */
AccidentInfoDlg.collectData = function () {
    var process = $("#report").val();
    var emergency = $("#emergencyProperty").val();
    this
        .set('id')
        .set('name')
        .set('accidentTypeId')
        .set('lineId')
        .set('stationId')
        .set('trainNumber')
        .set('interruptionTime')
        .set('trapPeoNum')
        .set('startTime')
        .set('accidentLevel')
        .set('interruptionType')
        .set('process',process)
        .set('emergencyId')
        .set('emergencyproId')
        .set('processJson')
        .set('endTime')


    ;
}

AccidentInfoDlg.accidentType = function () {
    return this.get('accidentTypeId');
}

/**
 * 提交添加
 */
AccidentInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();
    AccidentInfoDlg.set("processJson",AccidentInfoDlg.alarmprocessJson);

    AccidentInfoDlg.set("endTime",AccidentInfoDlg.getDataNow());
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/accident/add", function (data) {
        Feng.success("事故处理完成!");
        $("#accidentReport").attr("disabled",false);
        $("#finish").attr("disabled",true);
        AccidentInfoDlg.accidentId = data;
        location.reload();
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.accidentInfoData);
    ajax.start();
}

AccidentInfoDlg.getDataNow=function(){
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

AccidentInfoDlg.start = function () {
    var index = layer.open({
        type: 2,
        title: '选择预案',
        area: ['1000px', '600px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/counterplan/counterplan_sel'
    });
    this.layerIndex = index;
}

AccidentInfoDlg.openProcessExecute = function () {
    var index = layer.open({
        type: 2,
        title: '处置流程',
        area: ['1000px', '600px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/accident/process_execute'
    });
    this.layerIndex = index;
}

/**
 *打开编辑处置流程界面
 */
AccidentInfoDlg.openProcessEdit = function () {
    var index = layer.open({
        type: 2,
        title: '处置流程编辑',
        area: ['1000px', '600px'], //宽高
        fix: false, //不固定
        maxmin: false,
        content: Feng.ctxPath + '/counterplanAccident/process_edit'
    });
    this.layerIndex = index;
}

AccidentInfoDlg.report = function () {

    var index = layer.open({
        type: 2,
        title: '汇报通知',
        area: ['1600px', '600px'], //宽高
        fix: false, //不固定
        maxmin: false,
        content: Feng.ctxPath + '/mgr/all'
    });    this.layerIndex = index;
    layer.full(index);
}

AccidentInfoDlg.notice = function () {
    layer.msg('通知成功');
}


/**
 *提交修改
 */
AccidentInfoDlg.editSubmit = function () {

    this.clearData();
    this.collectData();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/accident/update", function (data) {
        Feng.success("修改成功!");
        window.parent.Accident.table.refresh();
        AccidentInfoDlg.close();
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.accidentInfoData);
    ajax.start();
}


/**
 * 出警时选择历史事故实例，返回处置流程json数据（rocessjson）
 */
AccidentInfoDlg.selectAccident = function (accidentId) {

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/accident/select", function (data) {
        AccidentInfoDlg.processJson = data.processJson;
    }, function (data) {

    });
    ajax.set("accidentId",accidentId);
    ajax.start();
}

/**
 * 出警时选择新增事故实例，返回处置流程json数据（rocessjson）
 */
AccidentInfoDlg.selectAccidentAdd = function (accidentId) {

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/accident/selectdisposaljson", function (data) {
        AccidentInfoDlg.disposalJson = data.disposalJson;
    }, function (data) {

    });
    ajax.set("accidentId",accidentId);
    ajax.start();
}

AccidentInfoDlg.selectAlarmProcess = function(){
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/alarm/processJson", function (data) {
        AccidentInfoDlg.alarmprocessJson = data.processJson;
        console.log(AccidentInfoDlg.alarmprocessJson);
    }, function (data) {

    });
    ajax.start();
}


/**
 * 判断是否符合公交联动启动条件
 */
AccidentInfoDlg.isStartPubBus = function(){
    var reduction = this.get("reduction"),interruptionTime = this.get("interruptionTime");
    if(reduction>=0.6 || interruptionTime>=20){
        return true;
    }
    return false;
}

/**
 * 检查事故车站是否有数据
 */
AccidentInfoDlg.check = function () {

    var interruptionTime = $("#interruptionTime").val();

    var retentionTime = $("#retentionTime").val();

    if(retentionTime == ""){
        Feng.info("请填写滞留时间");
        return false;
    }
    else if(interruptionTime == ""){
        Feng.info("请填写预计中断时间");
        return false;
    }
    else if($("#reduction").val()>=60){ //预计行车能力降低>=60
        return true;
    }
    else if($("#expectDelays").val()>=40){ //预计晚点》=40
        return true;
    }
    else if(($("#interruptionType").val()==2)&&($("#interruptionTime").val()>=20)){ //双向中断，中断时间大于20
        return true;
    }
    else if(($("#interruptionType").val()==1)&&($("#schedulingMode").val()==1)&&($("#schedulingModeMin").val()>=20)&&($("#interruptionTime").val()>=20)){
        return true;
    }
    else{
        Feng.info("未满足公交应急联动启动条件");
        return false;
    }
};

/**
 * 生成应急处置报告
 */
AccidentInfoDlg.accidentReportExport = function(){
    var accidentId = $("#accidentId").val();
    var index = layer.open({
        type: 2,
        title: '应急处置报告',
        area: ['1280px', '600px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/accident/dispose_report/'+ accidentId
    });
    this.layerIndex = index;
    layer.full(index);
}

/**
 * 显示tree
 */
AccidentInfoDlg.showAccidentTypeSelectTree = function () {
    Feng.showInputTree("accidentTypeName", "accidentTypeTreeDiv", 15, 34);
}
AccidentInfoDlg.onClickAccidentType = function (e, treeId, treeNode) {
    $("#accidentTypeName").attr("value", AccidentInfoDlg.accidentTypeTreeInstance.getSelectedVals());
    $("#accidentTypeId").attr("value", treeNode.id);
    $("#accidentTypeTreeDiv").fadeOut("fast");
}
AccidentInfoDlg.showLineTree = function () {
    Feng.showInputTree("lineName", "lineTreeDiv", 15, 34);
}
AccidentInfoDlg.onClickLine = function (e, treeId, treeNode) {
    if(treeNode.isParent){
        Feng.info("请选择线路");
        return;
    }

    $("#lineName").attr("value", AccidentInfoDlg.lineTreeInstance.getSelectedVal());
    $("#lineId").attr("value", treeNode.id);

    $("#stationName").attr("value", "");
    $("#stationId").attr("value", "");
    AccidentInfoDlg.initStationTree(treeNode.id);
    $("#lineTreeDiv").fadeOut("fast")
}

AccidentInfoDlg.initStationTree = function (lineId) {
    var stationTree = new $ZTree("stationTree","/roadnet/station/tree/"+lineId)
    stationTree.bindOnClick(AccidentInfoDlg.onClickStation);
    stationTree.init();
    AccidentInfoDlg.stationTreeInstance = stationTree;
}

AccidentInfoDlg.showStationTree = function () {
    if(!AccidentInfoDlg.stationTreeInstance){
        Feng.info("请选择线路");
    }
    Feng.showInputTree("stationName", "stationTreeDiv", 15, 34);
}
AccidentInfoDlg.onClickStation = function (e, treeId, treeNode) {
    $("#stationName").attr("value", AccidentInfoDlg.stationTreeInstance.getSelectedVal());
    $("#stationId").attr("value", treeNode.id);
}

AccidentInfoDlg.showEmergencySelectTree = function () {
    Feng.showInputTree("emergencyName", "emergencyTreeDiv", 15, 34);
}
AccidentInfoDlg.onClickEmergency = function (e, treeId, treeNode) {
    $("#emergencyName").attr("value", AccidentInfoDlg.emergencyTreeInstatce.getSelectedVal());
    $("#emergencyId").attr("value", treeNode.id);
}

/**
 * 验证数据是否为空
 */
AccidentInfoDlg.validate = function () {
    $('#accidentInfoForm').data("bootstrapValidator").resetForm();
    $('#accidentInfoForm').bootstrapValidator('validate');
    return $("#accidentInfoForm").data('bootstrapValidator').isValid();
};

/**
 * 突发事件属性选择
 */
AccidentInfoDlg.emergencyPropertySel = function () {
    var index = layer.open({
        type: 2,
        title: '请填写突发事件属性值',
        area: ['1200px', '600px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/accidentEmergencyproperty/accidentEmergencyproperty_add'
    });
    this.layerIndex = index;
};

/**
 * 突发事件属性选择
 */
AccidentInfoDlg.emergencyPropertyAssign = function (emergencyproId) {
    $("#emergencyproId").val(emergencyproId);
};

/**
 * 下载客流模板
 */
AccidentInfoDlg.exportXlsByM = function(){
    window.location.href = Feng.ctxPath + "/passengerNum/exportXlsByM";
}

AccidentInfoDlg.upload = function(){
    this.uploadInstance;
}

/**
 * 判断复选框的改变
 * @param key
 */
AccidentInfoDlg.checkChanged = function(key){
    $("#"+key).change(function(){
        if($("#"+key).prop('checked')){
            $("#"+key).attr("value", 1);
        }
        else{
            console.log("j进入不选中");
            $("#"+key).attr("value", 0);
        }
    });
}

/**
 * 判断复选框是否选中
 * @param key
 */
AccidentInfoDlg.isChecke = function(keys){
    for(var i =0;i<keys.length;i++){
        if( $("#"+keys[i]).val()==1){
            $("#"+keys[i]).attr("checked","checked");
        }
        else{
            continue;
        }
    }
}

/**
 * 电话
 */
AccidentInfoDlg.giveCall = function(){
    var index = layer.open({
        type: 2,
        title: '汇报通知',
        area: ['1600px', '600px'], //宽高
        fix: false, //不固定
        maxmin: false,
        content: Feng.ctxPath + '/contact/selectCall'
    });    this.layerIndex = index;
    layer.full(index);
}

/**
 * 短信
 */
AccidentInfoDlg.sendMessage = function(){
    var index = layer.open({
        type: 2,
        title: '汇报通知',
        area: ['1600px', '600px'], //宽高
        fix: false, //不固定
        maxmin: false,
        content: Feng.ctxPath + '/contact/selectMessage'
    });    this.layerIndex = index;
    layer.full(index);
}


$(function () {

    //每步操作
    $("#wizard").steps({
        bodyTag: "fieldset",
        forceMoveForward:true,
        startIndex:parseInt($("#currentIndex").val()),
        enablePagination:false
    });

    //接警页面初始化
    if($("#currentIndex").val()==0){
        if($("#step").val()>=1){
            $("#jiejing").attr("disabled", true);
            $("#ensure").attr("disabled", false);
        }
        else{
            $("#ensure").attr("disabled", true);
        }
    }

    //处警预案及事故事故实例列表初始化
    if($("#currentIndex").val()==1){
        if($("#step").val()==1){
            var queryData = {};
            queryData['accidentTypeId'] = $("#accidentTypeId").val();
            queryData['level'] = $("#accidentLevel").val();
            queryData['emergencyId'] = $("#emergencyId").val();
            queryData['emergencyproId'] = $("#emergencyproId").val();
            AccidentCounterplanSel.init(queryData);
        }
        else if($("#step").val()>=2){
            var queryData = {};
            queryData['accidentTypeId'] = $("#accidentTypeId").val();
            queryData['level'] = $("#accidentLevel").val();
            queryData['emergencyId'] = $("#emergencyId").val();
            queryData['emergencyproId'] = $("#emergencyproId").val();
            console.log(queryData);
            AccidentCounterplanSel.init(queryData);
            $("#chujing").attr("disabled", true);
        }
        else{
            // var div = document.getElementById('wizard');
            // div.style.cssText = 'background-color:  #000;opacity: 0.5;width:100%;height:100%;position:fixed;top:0;left:0;z-index:999;';
            // Feng.info("请先完成接警操作！");
        }

    }

    //编制处置流程数据信息初始化
    if($("#currentIndex").val()==2){
        if($("#step").val()==2){
            var counterplanId = $("#counterplanId").val();
            var type = $("#counterplanType").val();
            var json = null;
            if(type=="历史事故实例"){
                AccidentInfoDlg.selectAccident(counterplanId);
                json = AccidentInfoDlg.processJson;
            }
            if(type=="新增事故实例"){
                AccidentInfoDlg.selectAccidentAdd(counterplanId);
            }
            ProcessInfo.init(counterplanId,type,json);
        }
        else if($("#step").val()>=3){
            var counterplanId = $("#counterplanId").val();
            var type = $("#counterplanType").val();
            var json = null;
            if(type=="历史事故实例"){
                AccidentInfoDlg.selectAccident(counterplanId);
                json = AccidentInfoDlg.processJson;
            }
            if(type=="新增事故实例"){
                AccidentInfoDlg.selectAccidentAdd(counterplanId);
            }
            ProcessInfo.init(counterplanId,type,json);
            $("#editorFlow").attr("disabled", true);
        }
        else{
            var div = document.getElementById('wizard');
            div.style.cssText = 'background-color: #000;opacity: 0.5;width:100%;height:100%;position:fixed;top:0;left:0;z-index:999;';
            Feng.info("请先完成处警操作！");
        }
    }

    //处置阶段
    if($("#currentIndex").val()==3){
        if($("#step").val()==3){
            AccidentInfoDlg.selectAlarmProcess();
            ProcessExecuteInfo.init(AccidentInfoDlg.alarmprocessJson);
            $("#report").append($("#disposition_step_txt").val());
            if($("#disposition_step").val()){
                ProcessExecuteInfo.addSign($("#disposition_step").val().split(','));
            }
        }
        else if($("#step").val()>=4){
            AccidentInfoDlg.selectAlarmProcess();
            ProcessExecuteInfo.init(AccidentInfoDlg.alarmprocessJson);
            $("#report").append($("#disposition_step_txt").val());
            if($("#disposition_step").val()){
                ProcessExecuteInfo.addSign($("#disposition_step").val().split(','));
            }
            $("#finish").attr("disabled",true);
            $("#accidentReport").attr("disabled",false);
        }
        else{
            var div = document.getElementById('wizard');
            div.style.cssText = 'background-color: #000;opacity: 0.5;width:100%;height:100%;position:fixed;top:0;left:0;z-index:999;';
            Feng.info("请先完成编制处置流程操作！");
        }
    }

    Feng.initValidator("accidentInfoForm", AccidentInfoDlg.validateFields);

    var accidentTypeTree = new $ZTree("accidentTypeTree", "/accidentType/tree");
    accidentTypeTree.bindOnClick(AccidentInfoDlg.onClickAccidentType);
    accidentTypeTree.init();
    AccidentInfoDlg.accidentTypeTreeInstance = accidentTypeTree;

    var lineTree = new $ZTree("lineTree", "/roadnet/line/tree");
    lineTree.bindOnClick(AccidentInfoDlg.onClickLine);
    lineTree.init();
    AccidentInfoDlg.lineTreeInstance = lineTree;

    var emergencyTree = new $ZTree("emergencyTree", "/emergency/tree");
    emergencyTree.bindOnClick(AccidentInfoDlg.onClickEmergency);
    emergencyTree.init();
    AccidentInfoDlg.emergencyTreeInstatce = emergencyTree;

    var upload = new $WebUpload({
        uploadId:"upload",
        mimeTypes: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel",
        extensions: "xlsx,xls",
        url:"/passengerNum/importExcel",
        multiple:true
    });
    upload.init();
    AccidentInfoDlg.uploadInstance = upload;


    /**
     * 设置实时时间代码
     */
    function mytime(){
        var time = new Date();
        // 程序计时的月从0开始取值后+1
        var m = time.getMonth() + 1;
        var str;
        var week = time.getDay();
        if (week == 0) {
            str = "星期日";
        } else if (week == 1) {
            str = "星期一";
        } else if (week == 2) {
            str = "星期二";
        } else if (week == 3) {
            str = "星期三";
        } else if (week == 4) {
            str = "星期四";
        } else if (week == 5) {
            str = "星期五";
        } else if (week == 6) {
            str = "星期六";
        }
        var t = time.getFullYear() + "年" + m + "月"
            + time.getDate() + "日  " +str+" " +time.getHours() + "时"
            + time.getMinutes() + "分" + time.getSeconds()+"秒";
        document.getElementById("Time").innerHTML = t;
        document.getElementById("Time1").innerHTML = t;
    }
    setInterval(function() {mytime()},1000);

    //判断上下行
    var stream = $("#stream").val();
    if(stream==1){
        $("#upstream").prop("checked","checked");
    }
    else if(stream==2){
        $("#downstreeam").prop("checked","checked");
    }
    else{
        $("#upstream").prop("checked",false);
        $("#downstreeam").prop("checked",false);
    }
    //控制公交应急按钮
    $("#operationInterruption").change(function(){
        if($("#operationInterruption").prop('checked')){
            $("#busLinkage").attr("disabled", false);
            $("#operationInterruption").attr("value",1)
        }
        else{
            $("#busLinkage").attr("disabled", true);
            $("#operationInterruption").attr("value",0);
        }
    });
    $("#upstream").change(function(){
        if($("#upstream").prop('checked')){
            $("#stream").val(1);
        }
        if($("#downstreeam").prop('checked')){
            $("#downstreeam").attr("checked",false);
        }
    });
    $("#downstreeam").change(function(){
        if($("#upsdownstreeamtream").prop('checked')){
            $("#stream").val(2);
        }
        if($("#upstream").prop('checked')){
            $("#stream").val(2);
            $("#upstream").attr("checked",false);
        }
    });
    AccidentInfoDlg.checkChanged("closedStation");
    AccidentInfoDlg.checkChanged("trainClearingMan");
    AccidentInfoDlg.checkChanged("personalCasualty");
    AccidentInfoDlg.checkChanged("intervalEvacuation");
    AccidentInfoDlg.checkChanged("largePassenger");
    AccidentInfoDlg.checkChanged("otherCheck");
    AccidentInfoDlg.isChecke(["closedStation","trainClearingMan","personalCasualty","intervalEvacuation","largePassenger","otherCheck","operationInterruption"]);



});



